package com.lf.js;


import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by 10059 on 2018/7/9
 */
public class TestJavaScript {
    public static void main(String[] arg) throws IOException {

        ScriptEngineManager maneger = new ScriptEngineManager();
        ScriptEngine engine = maneger.getEngineByName("JavaScript");
        String jsFileName = "js/src/test.js";
        FileReader reader = new FileReader(jsFileName);   // 执行指定脚本
        if (engine != null) {
            try {
                // JS引擎解析文件
                engine.eval(reader);
                if (engine instanceof Invocable) {
                    Invocable invocable = (Invocable) engine;
                    // JS引擎调用方法
                    Object result = invocable.invokeFunction("add", 1, 2);
                    System.out.println("The result is: " + result);
                }
            } catch (ScriptException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } finally {
                reader.close();
            }
        } else {
            System.out.println("ScriptEngine create error!");
        }
    }
}

